package com.sailors.common.task.provider.domian.service.impl;

import com.sailors.common.task.provider.domian.convert.FileTaskEntityConver;
import com.sailors.common.task.provider.domian.factories.FileTaskEntityFactory;
import com.sailors.common.task.provider.domian.model.entity.FileTaskEntity;
import com.sailors.common.task.provider.domian.service.IFileTaskService;
import com.sailors.common.task.provider.faced.model.dto.execute.FileTaskCreateExecuteDto;
import com.sailors.common.task.provider.faced.model.dto.execute.FileTaskFailedExecuteDto;
import com.sailors.common.task.provider.faced.model.dto.execute.RefreshProcessExecuteDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * File task service
 *
 * @description:
 * @author: cyj
 * @date 2023 -02-22 00:20:30
 */
@Service
@Slf4j
public class FileTaskService implements IFileTaskService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(FileTaskCreateExecuteDto fileTaskCreateExecuteDto) {
        // 获取领域对象
        FileTaskEntity fileTaskEntity = FileTaskEntityFactory.obtain(fileTaskCreateExecuteDto);
        // 进行创建新任务
        fileTaskEntity.createNewCommon();
        return fileTaskEntity.getIdentify().getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshProcess(RefreshProcessExecuteDto refreshProcessExecuteDto) {
        // 获取领域对象
        FileTaskEntity fileTaskEntity = FileTaskEntityFactory.obtain(refreshProcessExecuteDto.getTaskId());
        // 如果源文件地址不为空则更新
        FileTaskEntityConver.INSTANCE.refreshProcess(refreshProcessExecuteDto, fileTaskEntity);
        // 更新
        fileTaskEntity.updateCommon();
        // 保存进度
        fileTaskEntity.saveProcess(FileTaskEntityConver.INSTANCE.refreshProcessExecuteDto2Val(refreshProcessExecuteDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void failed(FileTaskFailedExecuteDto fileTaskFailedExecuteDto) {
        // 获取领域对象
        FileTaskEntity fileTaskEntity = FileTaskEntityFactory.obtain(fileTaskFailedExecuteDto.getTaskId());
        // 更新任务
        fileTaskEntity.updateFailed(fileTaskFailedExecuteDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delayedFailed(Long taskId) {
        // 获取领域对象
        FileTaskEntity fileTaskEntity = FileTaskEntityFactory.obtain(taskId);
        // 延时失败
        fileTaskEntity.delayedFailed();
    }
}
